﻿using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using MiniX.Manage.Data;
using MiniX.Models;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Senparc.CO2NET.Extensions;
using Serilog.Core;
using Serilog;
using System.IO;
using Microsoft.Extensions.Configuration;
using System.Security.Claims;
using Microsoft.CodeAnalysis;

namespace MiniX.Manage.Controllers
{
    /// <summary>
    /// 版权所有: Copyright © 2023 Cloudin. 保留所有权利。
    /// 内容摘要: Base基类
    /// 创建日期：2023年4月9日
    /// 更新日期：2023年4月21日
    /// 版    本：V1.0.86 
    /// 作    者：Cloudin
    /// </summary>
    [Authorize]
    public class BaseController<T> : Controller
    {
        /// <summary>
        /// _context
        /// </summary>
        protected readonly MiniXManageContext _context;

        /// <summary>
        /// Log变量
        /// </summary>
        public Logger log;

        public BaseController(MiniXManageContext context)
        {
            _context = context;

            // 初始化日志
            log = new LoggerConfiguration()
             .ReadFrom.Configuration(new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
             .Build())
             .CreateLogger();
        }

        /// <summary>
        /// 获取管理员登录ID
        /// </summary>
        /// <returns></returns>
        public long GetUserID()
        {
            var user_id = User.FindFirst(ClaimTypes.Sid)!.Value;
            long.TryParse(user_id, out long get_user_id);

            return get_user_id;
        }

        /// <summary>
        /// 获取登录用户角色ID
        /// </summary>
        /// <returns></returns>
        public int GetRoleID()
        {
            int role_id = 0;
            var user_id = User.FindFirst(ClaimTypes.Sid)!.Value;
            long.TryParse(user_id, out long get_user_id);

            var item = _context.mini_users.FirstOrDefault(t => t.user_id == get_user_id);
            if (item != null)
            {
                role_id = item.role_id;
            }

            return role_id;
        }

        /// <summary>
        /// 获取配置信息ID对应的值
        /// </summary>
        /// <param name="info_id">配置信息ID</param>
        /// <returns></returns>
        public string? GetSettingInfoValue(int info_id)
        {
            var result = "";

            var item = _context.mini_setting_info.FirstOrDefault(t => t.setting_info_id == info_id);
            if (item != null)
            {
                if (item.type_id == 1)
                {
                    // 短内容
                    result = item.info_value;
                }
                else if (item.type_id == 2)
                {
                    // 长内容
                    result = item.info_content;
                }
                else if (item.type_id == 3)
                {
                    // 图片/文件
                    result = item.info_path;
                }
                else if (item.type_id == 4)
                {
                    // 布尔值
                    result = item.is_open ? "1" : "0";
                }
                else if (item.type_id == 5)
                {
                    // 链接
                    result = item.ext_link;
                }
                else if (item.type_id == 6)
                {
                    // 代码
                    result = item.ext_desc;
                }
                else
                {
                    result = item.info_value;
                }
            }

            return result;
        }

        /// <summary>
        /// 添加操作日志
        /// </summary>
        /// <param name="type_id">类型：4=新增，5=删除，6=修改，7=查询</param>
        /// <param name="log_code">日志标识</param>
        /// <param name="log_content">日志内容</param>
        public void AddLogs(int type_id, string log_code, string log_content)
        {
            try
            {
                var user_id = User.FindFirst(ClaimTypes.Sid)!.Value;
                long.TryParse(user_id, out long get_user_id);
                if (string.IsNullOrEmpty(user_id))
                {
                    user_id = "-1";
                }

                string page_url = HttpContext.Request.GetDisplayUrl();
                string referrer_url = HttpContext.Request.UrlReferrer();
                string user_agent = HttpContext.Request.UserAgent();
                string user_cookies = HttpContext.Request.Cookies.ToJson();

                // 根据配置信息添加日志
                var setting_info = _context.mini_setting_info.Where(t => t.parent_id == 14).ToList();
                setting_info.ForEach(c =>
                {
                    if (c.setting_info_id == 1400 && c.is_open && type_id == 4 || c.setting_info_id == 1401 && c.is_open && type_id == 5 || c.setting_info_id == 1402 && c.is_open && type_id == 6 || c.setting_info_id == 1403 && c.is_open && type_id == 7 || type_id == 1 || type_id == 16)
                    {
                        _context.mini_logs.Add(new Logs()
                        {
                            type_id = type_id,
                            user_id = get_user_id,
                            member_id = -1,
                            log_code = log_code,
                            platform_id = 1,
                            log_content = log_content,
                            client_ip = HttpContext.Connection.RemoteIpAddress!.ToString(),
                            page_url = page_url,
                            referrer_url = referrer_url,
                            user_agent = user_agent,
                            user_cookies = user_cookies,
                            log_remark = "",
                            created_at = DateTime.Now
                        });
                        _context.SaveChanges();
                    }
                });

            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> 添加操作日志");
            }
        }
    }
}
